package nl.hanze.designpatterns.DAO.impl.db;

import java.util.Iterator;

import nl.hanze.designpatterns.DAO.LoginCredentialDAO;
import nl.hanze.designpatterns.db.Executor;
import nl.hanze.designpatterns.domain.LoginCredential;

public class LoginCredentialDAOImpl implements LoginCredentialDAO {
	
	/**
	 * Method to get the right logincredentials
	 * @param username to get the right row from the database
	 * @return Logincredential object with the right username and password
	 * @throws Exception 
	 */
	public LoginCredential getCredential(String username) throws Exception{
		LoginCredential loginc = new LoginCredential(null,null);
		Executor ex = Executor.getInstance();
		String query ="SELECT * FROM logincredentials WHERE username='"+username+"'";
		Iterator <?> iterator = ex.getIterator(query,loginc.getClass());
		while(iterator.hasNext()){
			loginc = (LoginCredential)iterator.next();
		}
		return loginc;
	}

	@Override
	public boolean isValid(LoginCredential logincredential) {
		LoginCredential lc = null;
		String username = logincredential.getUserName();
		try {
			lc = getCredential(username);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if((lc.getUserName()==null)&&(lc.getPassword()==null)){
			return false;
		}
		else if((lc.getUserName().equals(logincredential.getUserName()))&&(lc.getPassword().equals(logincredential.getPassword()))){
			return true;
		}else{
			return false;
		}
	}
}
